#include "SmsMgr.h"
SmsMgr* SmsMgr::m_instance = 0;
SmsMgr* SmsMgr::Instance()
{
	if(0 == m_instance)
	{
		m_instance = new SmsMgr();
	}
	return m_instance;
}

SmsMgr::SmsMgr()
	:m_smshHandle(NULL)
	,m_smsmidMessageID(0)
{
	SmsOpen(SMS_MSGTYPE_TEXT, SMS_MODE_SEND, &m_smshHandle, NULL);
}

SmsMgr::~SmsMgr()
{
	SmsClose(m_smshHandle);
	m_instance = 0;
}

void SmsMgr::SendSMS(BOOL bSendConfirmation, BOOL bUseDefaultSMSC, LPCTSTR lpszSMSC, LPCTSTR lpszRecipient, LPCTSTR lpszMessage)
{
	// Create the source address
	if(!bUseDefaultSMSC)
	{
		m_smsaSource.smsatAddressType = SMSAT_INTERNATIONAL;
		_tcsncpy(m_smsaSource.ptsAddress, lpszSMSC, SMS_MAX_ADDRESS_LENGTH);
	}
	// Create the destination address
	m_smsaDestination.smsatAddressType = SMSAT_INTERNATIONAL;
	wchar_t phonenum[SMS_MAX_ADDRESS_LENGTH] = {0};
	_tcscpy(phonenum, L"+86");
	_tcscat(phonenum, lpszRecipient);
	_tcsncpy(m_smsaDestination.ptsAddress, phonenum, SMS_MAX_ADDRESS_LENGTH);
	// Set up provider specific data
	memset(&m_tpsd, 0, sizeof(m_tpsd));
	m_tpsd.dwMessageOptions = bSendConfirmation ? PS_MESSAGE_OPTION_STATUSREPORT : PS_MESSAGE_OPTION_NONE;
	m_tpsd.psMessageClass = PS_MESSAGE_CLASS1;
	m_tpsd.psReplaceOption = PSRO_NONE;
	m_tpsd.dwHeaderDataSize = 0;
	HRESULT hr = SmsSendMessage(m_smshHandle, ((bUseDefaultSMSC) ? NULL : &m_smsaSource), 
					&m_smsaDestination, NULL, (PBYTE) lpszMessage, 
					_tcslen(lpszMessage) * sizeof(TCHAR), (PBYTE) &m_tpsd, 
					sizeof(TEXT_PROVIDER_SPECIFIC_DATA), SMSDE_OPTIMAL, 
					SMS_OPTION_DELIVERY_NONE, &m_smsmidMessageID);
	if(S_OK != hr)
	{
		int err = GetLastError();
		wprintf(L"err = %d", err);
	}
}